package com.neuedu.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.hardware.display.DisplayManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.neuedu.myapplication.databinding.ActivityMainBinding;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    ActivityMainBinding binding;
    String token = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());


        //准备城市数据列表
        List<String> dataList = new ArrayList<>();
        dataList.add("北京市");
        dataList.add("上海市");
        dataList.add("广州市");
        dataList.add("深圳市");

        //创建一个适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item,dataList);

        //设置下拉样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        binding.spinner.setAdapter(adapter);

        binding.tv.setOnClickListener(v-> binding.spinner.performClick());

        //为Spinner 添加选择事件监听器
        binding.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectItem = (String) parent.getItemAtPosition(position);

                binding.tv.setText(selectItem);

                Intent broadcastIntent = new Intent("android.intent.weatherCityName");
                broadcastIntent.putExtra("cityName",selectItem);
                sendBroadcast(broadcastIntent);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                //没有选择任何项的处理逻辑
            }
        });

        startSecondDisplay();

        //天气，所有的接口token->身份验证，后端用来判断你是不是我这个系统当中的用户，你有没有权限获取我的信息
        login();
    }

    private void login() {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");

//        JSONObject jsonObject = new JSONObject();
//        try {
//            jsonObject.put("username","15666666666");
//            jsonObject.put("password","123456");
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }

        String json = "{\"username\":\"15666666666\",\"password\":\"123456\"}";

        OkHttpClient okHttpClient = new OkHttpClient();

        //创建RequestBody
        RequestBody body = RequestBody.create(mediaType,json);

        //创建Request对象
        Request request = new Request.Builder()
                .url(WeatherOkHttp.login)
                .post(body)
                .build();

        //创建异步请求
        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("Failure", "onFailure: " + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Gson gson = new Gson();
                LoginBean loginBean = gson.fromJson(WeatherOkHttp.getSuccess(response).toString(),LoginBean.class);
//                Log.i("onSuccess", "onResponse: " + loginBean.getToken());
                token = loginBean.getToken();
                SPManagerUtils.setToken(MainActivity.this,token);
                getWeatherData("北京市");
            }
        });
    }

    private void getWeatherData(String cityName) {
        //请求地址
        String url = WeatherOkHttp.weatherarea + cityName;
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization",token)
                .get()
                .build();

        OkHttpClient okHttpClient = new OkHttpClient();

        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Gson gson = new Gson();
//                Log.i("onSuccess", "onResponse: " + response.body().string());
                WeatherAreaBean areaBean = gson.fromJson(WeatherOkHttp.getSuccess(response).toString(),
                        WeatherAreaBean.class);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        binding.tv1.setText(areaBean.getData().getWind() + areaBean.getData().getIntervalTemperature());
                    }
                });
            }
        });
    }

    private void startSecondDisplay() {
        //通过getSystemService系统服务获取到了DisplayManager这个类的实例
        //DisplayManager是Android中用于管理屏幕的类，它可以提供所有的屏幕信息
        DisplayManager displayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
        //获取设备所有的显示屏，将这些屏幕存储到Display数组中
        Display[] displays = displayManager.getDisplays();
        //0 1 2
        if (displays.length > 1){
            Display display = displays[1];
            startSecondActivity(display);
        }
    }

    private void startSecondActivity(Display display) {
        //用于创建一个指定显示屏幕相关的上下文对象，这个上下文可以确保接下来的后续操作都是在这个显示屏的环境下操作
        Context displayContext = createDisplayContext(display);
        Intent intent = new Intent(displayContext,WeatherListActivity.class);
        //通过包名和类名去启动一个页面
        ComponentName componentName = new ComponentName("com.neuedu.myapplication",
                "com.neuedu.myapplication.WeatherListActivity");
        intent.setComponent(componentName);
        //通过getSystemService从应用的上下文对象获取ActivityManager的实例，管理系统当中所有Activity的相关操作
        ActivityManager activityManager = (ActivityManager) getApplicationContext().
                getSystemService(Activity.ACTIVITY_SERVICE);
        if (activityManager != null){
            //调用isActivityStartAllowedOnDisplay来判断是否允许在指定的屏幕上显示Activity
            boolean allowDisplay = activityManager.isActivityStartAllowedOnDisplay(
                    displayContext,display.getDisplayId(),intent);
            //如果允许的话,创建一个ActivityOptions对象，设置启动的显示屏ID
            if (allowDisplay){
                ActivityOptions options = ActivityOptions.makeBasic();
                options.setLaunchDisplayId(display.getDisplayId());
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent,options.toBundle());
            }
        }
    }
}